<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择地点位置"
    width="700px" align-center
    :before-close="handleCancel"
    top="6vh"
    class="location-select-dialog"
  >
    <div class="location-select-container">
      <!-- 搜索栏和操作按钮分组 -->
      <div class="search-bar-group">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索地点位置..."
          prefix-icon="el-icon-search"
          clearable
          @input="handleSearch"
          size="default"
          class="search-input"
        />
        <el-button type="primary" size="small" class="add-root-btn" @click="handleAddRoot">
          <el-icon><Plus /></el-icon>
          <span>添加建筑</span>
        </el-button>
      </div>
      <!-- 当前选择显示 -->
      <div v-if="selectedLocation" class="selected-info-card">
        <span class="selected-label">当前选择：</span>
        <el-tag type="primary" size="default" closable @close="clearSelection">
          <span class="selected-path">{{ getLocationPath(selectedLocation) }}</span>
        </el-tag>
      </div>
      <!-- 树形控件 -->
      <div v-loading="loading" element-loading-text="正在加载地点位置数据...">
        <el-tree
          v-if="filteredLocationTree.length > 0"
          ref="treeRef"
          :data="filteredLocationTree"
          :props="{ children: 'children', label: 'name' }"
          node-key="id"
          :show-checkbox="false"
          :default-expand-all="false"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          :highlight-current="true"
          class="location-tree simple-tree"
        >
          <template #default="{ node, data }">
            <div class="tree-node" :class="{ 'selected': selectedLocation?.id === data.id }">
              <span class="node-icon">
                <i v-if="data.type === 'building'" class="el-icon-office-building" style="color: #409eff;"></i>
                <i v-else-if="data.type === 'floor'" class="el-icon-menu" style="color: #67c23a;"></i>
                <i v-else-if="data.type === 'room'" class="el-icon-house" style="color: #e6a23c;"></i>
              </span>
              <span class="node-label">{{ data.name }}</span>
              <span class="node-type">[{{ getTypeLabel(data.type) }}]</span>
              <!-- 操作按钮组 -->
              <div class="node-actions simple-actions">
                <el-tooltip content="编辑" placement="top">
                  <el-button size="small" circle type="warning" @click.stop="handleEdit(data)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-tooltip content="子项" placement="top">
                  <el-button size="small" circle type="success" @click.stop="handleAdd(data)">
                    <el-icon><FolderAdd /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-tooltip content="同级" placement="top">
                  <el-button size="small" circle type="primary" @click.stop="handleAddSibling(data)">
                    <el-icon><Plus /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-tooltip v-if="!data.children || data.children.length === 0" content="删除" placement="top">
                  <el-button size="small" circle type="danger" @click.stop="handleDelete(data)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-tree>
        <!-- 无数据时的空状态显示 -->
        <div v-else-if="!loading && currentTenantId" class="empty-state">
          <div class="empty-icon">
            <el-icon size="56" style="color: #409eff;"><OfficeBuilding /></el-icon>
          </div>
          <div class="empty-title">暂无地点位置数据</div>
          <div class="empty-description">
            当前商户下还没有创建任何地点位置，请先在地点位置管理中创建
          </div>
        </div>
        <!-- 商户ID缺失时的提示 -->
        <div v-else-if="!loading && !currentTenantId" class="no-tenant-state">
          <div class="empty-icon">
            <el-icon size="56" style="color: #e17055;"><QuestionFilled /></el-icon>
          </div>
          <div class="empty-title">缺少商户信息</div>
          <div class="empty-description">
            无法加载地点位置数据，请确保已正确设置商户ID
          </div>
        </div>
      </div>
    </div>
    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          size="large" 
          @click="handleConfirm"
          :disabled="!selectedLocation"
        >
          确定选择
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加节点表单对话框 -->
  <el-dialog
    v-model="addDialogVisible"
    :title="addDialogTitle"
    width="480px" align-center
    :before-close="handleAddDialogClose"
  >
    <el-form 
      ref="addFormRef" 
      :model="addForm" 
      :rules="addFormRules" 
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="名称" prop="name">
        <el-input 
          v-model="addForm.name" 
          :placeholder="`请输入${addDialogTypeLabel}名称`"
          clearable
          maxlength="50"
          show-word-limit
          @keyup.enter="submitAddForm"
        />
      </el-form-item>
      <el-form-item label="排序序号" prop="orderNum">
        <el-input-number 
          v-model="addForm.orderNum" 
          :min="0" 
          :max="99999"
          :step="100"
          controls-position="right"
          placeholder="请输入排序序号（可选）"
          style="width: 100%;"
        />
        <div style="color: #909399; font-size: 12px; margin-top: 4px;">
          选填，数字越大排序越靠前，留零则自动排序最前
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleAddDialogClose">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑节点表单对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    :title="`编辑${editDialogTypeLabel}`"
    width="480px" align-center
    :before-close="handleEditDialogClose"
  >
    <el-form 
      ref="editFormRef" 
      :model="editForm" 
      :rules="editFormRules" 
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="名称" prop="name">
        <el-input 
          v-model="editForm.name" 
          :placeholder="`请输入${editDialogTypeLabel}名称`"
          clearable
          maxlength="50"
          show-word-limit
          @keyup.enter="submitEditForm"
        />
      </el-form-item>
      <el-form-item label="排序序号" prop="orderNum">
        <el-input-number 
          v-model="editForm.orderNum" 
          :min="0" 
          :max="99999"
          :step="100"
          controls-position="right"
          placeholder="请输入排序序号（可选）"
          style="width: 100%;"
        />
        <div style="color: #909399; font-size: 12px; margin-top: 4px;">
          选填，数字越大排序越靠前，留零则自动排序最前
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleEditDialogClose">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, defineExpose } from 'vue'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import {
  OfficeBuilding,
  QuestionFilled,
  Plus,
  Delete,
  FolderAdd,
  Edit
} from '@element-plus/icons-vue'
import { getLocationTree, addLocation, deleteLocation, editLocation } from '@/api/settle'
import { 
  LocationTreeNode, 
  LocationType,
  LocationTypeLabels 
} from '@/api/types/location'

// 添加节点表单相关
interface AddForm {
  name: string
  orderNum: number
}

interface AddDialogConfig {
  type: 'child' | 'sibling' | 'root'
  parentNode?: LocationTreeNode
  childType?: string
}

const addDialogVisible = ref(false)
const addFormRef = ref<FormInstance>()
const addForm = ref<AddForm>({
  name: '',
  orderNum: 0
})
const addDialogConfig = ref<AddDialogConfig>({
  type: 'root'
})

const addFormRules: FormRules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 1, max: 50, message: '名称长度在 1 到 50 个字符', trigger: 'blur' },
    { pattern: /\S+/, message: '名称不能为空', trigger: 'blur' }
  ],
  orderNum: []
}

const addDialogTitle = computed(() => {
  const { type, parentNode, childType } = addDialogConfig.value
  if (type === 'root') {
    return '添加新建筑'
  } else if (type === 'child') {
    return `添加${getTypeLabel(childType || '')} - 父级：${parentNode?.name}`
  } else if (type === 'sibling') {
    return `添加同级${getTypeLabel(parentNode?.type || '')} - 同级于：${parentNode?.name}`
  }
  return '添加节点'
})

const addDialogTypeLabel = computed(() => {
  const { type, parentNode, childType } = addDialogConfig.value
  if (type === 'root') {
    return '建筑'
  } else if (type === 'child') {
    return getTypeLabel(childType || '')
  } else if (type === 'sibling') {
    return getTypeLabel(parentNode?.type || '')
  }
  return ''
})

// 编辑节点表单相关
interface EditForm {
  id: number
  name: string
  orderNum: number
  locationType: string
  parentId?: number
  tenantId?: number
}

const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = ref<EditForm>({
  id: 0,
  name: '',
  orderNum: 0,
  locationType: '',
  parentId: undefined,
  tenantId: undefined
})
const editingNode = ref<LocationTreeNode | null>(null)

const editFormRules: FormRules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 1, max: 50, message: '名称长度在 1 到 50 个字符', trigger: 'blur' },
    { pattern: /\S+/, message: '名称不能为空', trigger: 'blur' }
  ],
  orderNum: []
}

const editDialogTypeLabel = computed(() => {
  if (editingNode.value) {
    return getTypeLabel(editingNode.value.type)
  }
  return ''
})

// 组件属性
const emit = defineEmits(['confirm'])

// 响应式数据
const dialogVisible = ref(false)
const treeRef = ref()
const searchKeyword = ref('')
const loading = ref(false)
const currentTenantId = ref<number | undefined>()
const selectedLocation = ref<LocationTreeNode | null>(null)

// 地点位置数据
const fullLocationTree = ref<LocationTreeNode[]>([])

// 加载API数据
const loadLocationData = async () => {
  try {
    loading.value = true
    
    if (!currentTenantId.value) {
      ElMessage.error('缺少商户信息，无法加载地点位置数据')
      fullLocationTree.value = []
      return
    }
    
    const res = await getLocationTree(currentTenantId.value)
    
    if (res.success && res.data) {
      fullLocationTree.value = res.data
    } else {
      const errorMsg = res.msg || res.message || '加载地点位置数据失败'
      ElMessage.error(`加载失败: ${errorMsg}`)
      fullLocationTree.value = []
    }
  } catch (error) {
    ElMessage.error('网络请求失败，请检查网络连接后重试')
    fullLocationTree.value = []
  } finally {
    loading.value = false
  }
}

// 计算属性
// 过滤后的树数据（支持搜索）
const filteredLocationTree = computed(() => {
  let result = fullLocationTree.value
  
  // 如果有搜索关键词，进行搜索过滤
  if (searchKeyword.value.trim()) {
    result = searchFilterTree(result)
  }
  
  return result
})

// 搜索过滤函数
const searchFilterTree = (nodes: LocationTreeNode[]): LocationTreeNode[] => {
  return nodes
    .map(node => {
      const filteredNode = { ...node }
      
      if (node.children) {
        const filteredChildren = searchFilterTree(node.children)
        if (filteredChildren.length > 0) {
          filteredNode.children = filteredChildren
        } else {
          delete filteredNode.children
        }
      }
      
      return filteredNode
    })
    .filter(node => {
      // 检查当前节点是否匹配搜索关键词
      const matchesSearch = node.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
      
      // 检查子节点是否有匹配的
      const hasMatchingChildren = node.children && node.children.length > 0
      
      return matchesSearch || hasMatchingChildren
    })
}

// 获取类型标签
const getTypeLabel = (type: string) => {
  return LocationTypeLabels[type as LocationType] || '未知'
}

// 获取位置路径
const getLocationPath = (location: LocationTreeNode): string => {
  const path: string[] = []
  
  // 递归查找路径
  const findPath = (nodes: LocationTreeNode[], targetId: string | number, currentPath: string[] = []): boolean => {
    for (const node of nodes) {
      const newPath = [...currentPath, node.name]
      
      if (node.id === targetId) {
        path.push(...newPath)
        return true
      }
      
      if (node.children && findPath(node.children, targetId, newPath)) {
        return true
      }
    }
    return false
  }
  
  findPath(fullLocationTree.value, location.id)
  return path.join(' -> ') || location.name
}

// 获取子类型
const getChildType = (parentType: string): string | null => {
  switch (parentType) {
    case 'building': return 'floor'
    case 'floor': return 'room'
    default: return null
  }
}

// 获取删除按钮提示
const getDeleteTooltip = (node: LocationTreeNode) => {
  const hasChildren = node.children && node.children.length > 0
  if (hasChildren) {
    const childCount = node.children!.length
    return `删除 "${node.name}" 及其 ${childCount} 个子项`
  }
  return `删除 "${node.name}"`
}

// 打开添加对话框
const openAddDialog = (type: 'child' | 'sibling' | 'root', node?: LocationTreeNode, childType?: string) => {
  // 重置表单
  addForm.value = {
    name: '',
    orderNum: 0
  }
  
  // 设置配置
  addDialogConfig.value = {
    type,
    parentNode: node,
    childType
  }
  
  // 清空验证
  addFormRef.value?.clearValidate()
  
  // 显示对话框
  addDialogVisible.value = true
}

// 关闭添加对话框
const handleAddDialogClose = () => {
  addDialogVisible.value = false
  addFormRef.value?.resetFields()
}

// 提交添加表单
const submitAddForm = async () => {
  if (!addFormRef.value) return
  
  await addFormRef.value.validate((valid) => {
    if (valid) {
      const { type, parentNode, childType } = addDialogConfig.value
      const { name, orderNum } = addForm.value
      
      // 直接传递，由各添加函数统一处理默认值
      if (type === 'root') {
        addRootBuilding(name, orderNum)
      } else if (type === 'child' && parentNode && childType) {
        addChildNode(parentNode, childType, name, orderNum)
      } else if (type === 'sibling' && parentNode) {
        addSiblingNode(parentNode, name, orderNum)
      }
      
      handleAddDialogClose()
    }
  })
}

// 新增同级节点
const handleAddSibling = (node: LocationTreeNode) => {
  openAddDialog('sibling', node)
}

// 新增子节点
const handleAdd = (node: LocationTreeNode) => {
  const childType = getChildType(node.type)
  if (!childType) {
    ElMessage.warning(`${getTypeLabel(node.type)}不能添加子项`)
    return
  }
  openAddDialog('child', node, childType)
}

// 新增根建筑
const handleAddRoot = () => {
  openAddDialog('root')
}

// 打开编辑对话框
const handleEdit = (node: LocationTreeNode) => {
  console.log(node)
  editingNode.value = node
  editForm.value = {
    id: node.id,
    name: node.name,
    orderNum: node.orderNum || 0,
    locationType: node.locationType || node.type,
    parentId: node.parentId
  }
  
  // 清空验证
  editFormRef.value?.clearValidate()
  
  // 显示对话框
  editDialogVisible.value = true
}

// 关闭编辑对话框
const handleEditDialogClose = () => {
  editDialogVisible.value = false
  editFormRef.value?.resetFields()
  editingNode.value = null
}

// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate((valid) => {
    if (valid) {
      const { id, name, orderNum, locationType, parentId } = editForm.value
      
      updateNode(id, name, orderNum, locationType, parentId)
      handleEditDialogClose()
    }
  })
}

// 更新节点
const updateNode = async (
  nodeId: number,
  newName: string,
  orderNum?: number,
  locationType?: string,
  parentId?: number
) => {
  try {
    loading.value = true
    const updateRequest: any = {
      id: nodeId,
      name: newName,
      locationType: locationType,
      parentId: parentId,
      tenantId: currentTenantId.value,
      orderNum: orderNum !== undefined ? orderNum : 0
    }
    
    const res = await editLocation(updateRequest)
    if (res.success) {
      ElMessage.success('编辑成功')
      // 构造新节点
      const editNode: LocationTreeNode = {
        id: updateRequest.id,
        name: updateRequest.name,
        type: updateRequest.locationType,
        locationType: updateRequest.locationType,
        parentId: updateRequest.parentId,
        tenantId: updateRequest.tenantId,
        orderNum: updateRequest.orderNum
      }
      // 本地更新节点
      if (!updateNodeInTree(editNode, parentId)) {
        // 如果本地更新失败，则重新加载整个树
        await loadLocationData()
      }
  
      // 如果更新的是当前选中的节点，同步更新选中状态
      if (selectedLocation.value?.id === nodeId) {
        selectedLocation.value.name = newName
        if (orderNum !== undefined) {
          selectedLocation.value.orderNum = orderNum
        }
      }
    } else {
      ElMessage.error(`编辑失败: ${res.msg || '未知错误'}`)
    }
  } catch {
    ElMessage.error('编辑失败')
  } finally {
    loading.value = false
  }
}

// 在树中更新旧节点（本地更新，避免重新查询）
const updateNodeInTree = (editNode: LocationTreeNode, parentId?: number | null) => {
  // 如果没有父节点，添加到根级别
  if (parentId === undefined || parentId === null) {
    for (const node of fullLocationTree.value) {
      if (node.id === editNode.id) {
        // 找到节点，更新信息
        node.name = editNode.name
        node.orderNum = editNode.orderNum
        console.log('更新节点', node.name, node.orderNum) // 调试信息
        break
      }
    }
    // 按照 orderNum 排序
    fullLocationTree.value.sort((a, b) => (b.orderNum || 0) - (a.orderNum || 0))
    return true
  }
  
  // 递归查找父节点并插入
  const findAndUpdate = (nodes: LocationTreeNode[]): boolean => {
    for (const node of nodes) {
      if (node.id === parentId) {
        if (!node.children) {
          continue
        }
        for (const child of node.children) {
          if (child.id === editNode.id) {
            // 找到节点，更新信息
            child.name = editNode.name
            child.orderNum = editNode.orderNum
            console.log('更新节点', child.name, child.orderNum) // 调试信息
            break
          }
        }
        // 按照 orderNum 排序
        node.children.sort((a, b) => (b.orderNum || 0) - (a.orderNum || 0))
        return true
      }
      
      // 继续在子节点中查找
      if (node.children && findAndUpdate(node.children)) {
        return true
      }
    }
    return false
  }
  
  return findAndUpdate(fullLocationTree.value)
}

// 在树中插入新节点（本地更新，避免重新查询）
const insertNodeToTree = (newNode: LocationTreeNode, parentId?: number | null) => {
  // 如果没有父节点，添加到根级别
  if (parentId === undefined || parentId === null) {
    fullLocationTree.value.push(newNode)
    // 按照 orderNum 排序
    fullLocationTree.value.sort((a, b) => (b.orderNum || 0) - (a.orderNum || 0))
    return true
  }
  
  // 递归查找父节点并插入
  const findAndInsert = (nodes: LocationTreeNode[]): boolean => {
    for (const node of nodes) {
      if (node.id === parentId) {
        // 找到父节点，初始化 children 数组
        if (!node.children) {
          node.children = []
        }
        node.children.push(newNode)
        // 按照 orderNum 排序
        node.children.sort((a, b) => (b.orderNum || 0) - (a.orderNum || 0))
        return true
      }
      
      // 继续在子节点中查找
      if (node.children && findAndInsert(node.children)) {
        return true
      }
    }
    return false
  }
  
  return findAndInsert(fullLocationTree.value)
}

const addSiblingNode = async (node: LocationTreeNode, siblingName: string, orderNum?: number) => {
  try {
    loading.value = true
    const addRequest: any = {
      name: siblingName,
      locationType: node.locationType || node.type,
      parentId: node.parentId,
      tenantId: currentTenantId.value,
      orderNum: orderNum !== undefined ? orderNum : 0
    }
    const res = await addLocation(addRequest)
    if (res.success && res.data) {
      ElMessage.success('添加成功')
      // 构造新节点
      const newNode: LocationTreeNode = {
        id: res.data.id,
        name: siblingName,
        type: node.type,
        locationType: node.locationType || node.type,
        parentId: node.parentId,
        tenantId: currentTenantId.value,
        orderNum: res.data.orderNum,
        children: []
      }
      // 本地插入节点
      if (!insertNodeToTree(newNode, node.parentId)) {
        // 如果本地插入失败，则重新加载整个树
        await loadLocationData()
      }
    } else {
      ElMessage.error(`添加失败: ${res.msg || '未知错误'}`)
    }
  } catch {
    ElMessage.error('添加失败')
  } finally {
    loading.value = false
  }
}

const addChildNode = async (parentNode: LocationTreeNode, childType: string, childName: string, orderNum?: number) => {
  try {
    loading.value = true
    const addRequest: any = {
      name: childName,
      locationType: childType,
      parentId: typeof parentNode.id === 'string' ? parseInt(parentNode.id) : parentNode.id,
      tenantId: currentTenantId.value,
      orderNum: orderNum !== undefined ? orderNum : 0
    }
    const res = await addLocation(addRequest)
    if (res.success && res.data) {
      ElMessage.success('添加成功')
      // 构造新节点
      const newNode: LocationTreeNode = {
        id: res.data.id,
        name: childName,
        type: childType,
        locationType: childType,
        parentId: typeof parentNode.id === 'string' ? parseInt(parentNode.id) : parentNode.id,
        tenantId: currentTenantId.value,
        orderNum: res.data.orderNum,
        children: []
      }
      // 本地插入节点
      if (!insertNodeToTree(newNode, newNode.parentId)) {
        // 如果本地插入失败，则重新加载整个树
        await loadLocationData()
      }
    } else {
      ElMessage.error(`添加失败: ${res.msg || '未知错误'}`)
    }
  } catch {
    ElMessage.error('添加失败')
  } finally {
    loading.value = false
  }
}

const addRootBuilding = async (buildingName: string, orderNum?: number) => {
  try {
    loading.value = true
    const addRequest: any = {
      name: buildingName,
      locationType: 'building',
      parentId: undefined,
      tenantId: currentTenantId.value,
      orderNum: orderNum !== undefined ? orderNum : 0
    }
    const res = await addLocation(addRequest)
    if (res.success && res.data) {
      ElMessage.success('添加建筑成功')
      // 构造新节点
      const newNode: LocationTreeNode = {
        id: res.data.id,
        name: buildingName,
        type: 'building',
        locationType: 'building',
        parentId: undefined,
        tenantId: currentTenantId.value,
        orderNum: res.data.orderNum,
        children: []
      }
      // 本地插入节点
      insertNodeToTree(newNode, undefined)
    } else {
      ElMessage.error(`添加失败: ${res.msg || '未知错误'}`)
    }
  } catch {
    ElMessage.error('添加失败')
  } finally {
    loading.value = false
  }
}

// 删除节点
const handleDelete = (data: LocationTreeNode) => {
  if (loading.value) {
    ElMessage.warning('正在加载中，请稍后再试')
    return
  }
  if (!data.id || !data.name) {
    ElMessage.error('节点数据不完整，无法执行删除操作')
    return
  }
  ElMessageBox.confirm(getDeleteTooltip(data), '删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true
  }).then(() => {
    deleteNode(data.id, data.name)
  })
}

// 从树中删除节点（本地更新，避免重新查询）
const removeNodeFromTree = (nodeId: string | number): boolean => {
  // 从根级别删除
  const rootIndex = fullLocationTree.value.findIndex(node => node.id === nodeId)
  if (rootIndex !== -1) {
    fullLocationTree.value.splice(rootIndex, 1)
    return true
  }
  
  // 递归查找并删除
  const findAndRemove = (nodes: LocationTreeNode[]): boolean => {
    for (let i = 0; i < nodes.length; i++) {
      const node = nodes[i]
      
      // 检查子节点中是否有要删除的节点
      if (node.children) {
        const childIndex = node.children.findIndex(child => child.id === nodeId)
        if (childIndex !== -1) {
          node.children.splice(childIndex, 1)
          return true
        }
        
        // 继续在更深层的子节点中查找
        if (findAndRemove(node.children)) {
          return true
        }
      }
    }
    return false
  }
  
  return findAndRemove(fullLocationTree.value)
}

const deleteNode = async (nodeId: string | number, nodeName?: string) => {
  try {
    loading.value = true
    const numericId = typeof nodeId === 'string' ? parseInt(nodeId) : nodeId
    const res = await deleteLocation(numericId)
    if (res.success) {
      ElMessage.success(nodeName ? `已成功删除"${nodeName}"` : '删除成功')
      // 本地删除节点
      if (!removeNodeFromTree(nodeId)) {
        // 如果本地删除失败，则重新加载整个树
        await loadLocationData()
      }
      // 如果删除的是当前选中的节点，清除选择
      if (selectedLocation.value?.id === nodeId) {
        selectedLocation.value = null
      }
    } else {
      ElMessage.error(`删除失败: ${res.msg || '未知错误'}`)
    }
  } catch {
    ElMessage.error('删除失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  // 搜索功能已通过计算属性实现
}

// 处理节点点击
const handleNodeClick = (data: LocationTreeNode) => {
  selectLocation(data)
}

// 选择位置
const selectLocation = (location: LocationTreeNode) => {
  selectedLocation.value = location
  //ElMessage.success(`已选择: ${getLocationPath(location)}`)
}

// 清除选择
const clearSelection = () => {
  selectedLocation.value = null
}

// 处理确认
const handleConfirm = () => {
  if (!selectedLocation.value) {
    ElMessage.warning('请先选择一个地点位置')
    return
  }
  
  // 构建完整的地点位置信息，包含路径
  const locationWithPath = {
    ...selectedLocation.value,
    path: getLocationPath(selectedLocation.value)
  }
  
  emit('confirm', locationWithPath)
  dialogVisible.value = false
}

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false
  selectedLocation.value = null
  searchKeyword.value = ''
}

// 打开对话框
const openDialog = async (tenantId?: number) => {
  dialogVisible.value = true
  selectedLocation.value = null
  searchKeyword.value = ''
  
  // 设置当前商户ID
  if (tenantId) {
    currentTenantId.value = tenantId
  } else {
    currentTenantId.value = undefined
  }
  
  try {
    // 加载数据
    await loadLocationData()
  } catch (error) {
    ElMessage.error('初始化失败，请重试')
  }
}

// 暴露方法
defineExpose({
  openDialog
})
</script>

<style scoped>
.location-select-container {
  max-height: 500px;
  padding: 0 8px 8px 8px;
}
.search-bar-group {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}
.add-root-btn {
  border-radius: 16px;
  min-width: 90px;
  font-size: 14px;
  padding: 0 16px;
  height: 32px;
  box-shadow: none;
}
.selected-info-card {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f6faff;
  border: 1px solid #e3eaf3;
  border-radius: 8px;
  padding: 6px 14px;
  margin-bottom: 8px;
  font-size: 14px;
}
.selected-label {
  color: #409eff;
  font-weight: 500;
}
.selected-path {
  font-weight: 500;
}
.location-tree.simple-tree {
  max-height: 340px;
  overflow-y: auto;
  border: 1px solid #e3eaf3;
  border-radius: 6px;
  padding: 6px 4px;
  background: #fcfdff;
}
.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 4px 0;
  padding-right: 160px; /* 预留空间 */
  border-radius: 4px;
  transition: background 0.15s;
  font-size: 15px;
  position: relative; /* 定位的子元素 */
}
.tree-node:hover {
  background-color: #f3f8fd;
}
.tree-node.selected {
  background-color: #eaf6ff;
  border: 1px solid #409eff44;
}
.node-icon {
  margin-right: 8px;
  color: #409eff;
  font-size: 18px;
}
.node-label {
  font-weight: 500;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.node-type {
  margin-left: 8px;
  font-size: 12px;
  color: #b0b4bb;
}
.simple-actions {
  display: flex;
  gap: 2px;
  opacity: 0;
  transition: opacity 0.18s;
  position: absolute; /* 绝对定位 */
  right: 8px; /* 固定在右侧 */
  top: 50%; /* 垂直居中 */
  transform: translateY(-50%); /* 垂直居中对齐 */
}
.tree-node:hover .simple-actions {
  opacity: 1;
}
.simple-actions .el-button {
  border-radius: 50%;
  padding: 0;
  min-width: 24px;
  height: 24px;
  font-size: 13px;
  box-shadow: none;
}
.simple-actions .el-button--info {
  background: #eaf1fa;
  color: #409eff;
  border: none;
}
.simple-actions .el-button--info:hover {
  background: #409eff;
  color: #fff;
}
.empty-state,
.no-tenant-state {
  text-align: center;
  padding: 40px 12px;
  border-radius: 10px;
  border: 1px solid #e4e7ed;
  background: #f8fafc;
  margin-top: 18px;
}
.empty-icon {
  margin-bottom: 16px;
}
.empty-title {
  font-size: 17px;
  color: #303133;
  margin-bottom: 8px;
  font-weight: 600;
}
.empty-description {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
}
.dialog-footer {
  text-align: center;
}
</style>